package eic.service;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import eic.dao.EmployeeDAO;
import eic.dao.UserDAO;
import eic.dao.impl.EmployeeImpl;
import eic.dao.impl.UserImpl;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import test.dao.DaoTest;
import utils.AppKeyCreator;
import utils.JsonTool;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Tang on 2015/7/5.
 */
public class UserAuthService {

    EmployeeDAO employeeDAO ;
    ObjectMapper objectMapper ;
    JsonGenerator jsonGenerator ;

    public UserAuthService(){
        objectMapper = new ObjectMapper();
    }

    public String getUnregisterList(){
        employeeDAO = new EmployeeImpl() ;
        List list = employeeDAO.getUnregisterList();
        Map<String,Object> map = new HashMap<String, Object>();
        if(list == null) {
            map.put("code",500);
            map.put("error","数据查询出错");
        }
        String array = JsonTool.listToJsonString(list);
        map.put("code","200");
        map.put("data",list);
        return JsonTool.mapToJsonString(map);
    }

    public String registerUser(String phone , String password , String id){

        Map<String ,Object> map = new HashMap<String, Object>();

        // 判断请求参数是否正确
        if (phone ==null || password==null || id==null){
            map.put("code",400);
            map.put("error","请求错误！");
            return JsonTool.mapToJsonString(map);
        }

        // 检测用户是否存在
        EmployeeDAO employeeDAO = new EmployeeImpl();
        boolean isExist = employeeDAO.isExistEmployee(Integer.valueOf(id));
        if (!isExist){
            map.put("code",400);
            map.put("error","该用户不存在！");
            return JsonTool.mapToJsonString(map);
        }

        // 在User表添加用户，同时返回数据
        UserDAO dao = new UserImpl();
        String appkey = AppKeyCreator.create(id);
        boolean sign = dao.addUser(phone,password,id,appkey);
        if (sign){
            map.put("code",200);
            map.put("appkey",appkey);
            //String formatId = String.format("%05d",id);
            //map.put("id",id);
        }else{
            map.put("code",500);
            map.put("error","服务器错误！");
        }

        // 修改Employee中对应的域为注册状态
        boolean registerSuccess = employeeDAO.registerEmployee(Integer.valueOf(id));
        if (!registerSuccess){
            map.put("code",500);
            map.put("error","服务器错误");
            map.put("from","Employee");
            return JsonTool.mapToJsonString(map);
        }

        return  JsonTool.mapToJsonString(map);

    }

}
